package com.zilu.digitaltwin.service;

import com.alibaba.cosmo.remote.httpclient.HttpMethod;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zilu.digitaltwin.common.manager.DataQManager;
import com.zilu.digitaltwin.dto.dataq.TableColumnDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class ModelTableService {

    @Autowired
    private DataQManager dataQManager;

    @Value("${dataq.tenant.code}")
    private String tenantCode;

    @Value("${dataq.workspace.id}")
    private String workspaceId;

    @Value("${dataq.user.id}")
    private String userId;

    /**
     * 根据逻辑表code和type获取物理表的字段情况
     *
     * @param code
     * @return
     */
    public List<TableColumnDTO> listColumnByCode(String code) {
        JSONObject byCode = this.getByCode(code);
        return JSONArray.parseArray(byCode.getString("columns"), TableColumnDTO.class);
    }

    /**
     * 根据表名获取逻辑表信息
     *
     * @param code
     * @return
     */
    public JSONObject getByCode(String code) {
        String pathUrl = "datamodeling/v4/meta/table/getByCode";
        Map<String, Object> queryParam = new HashMap<>(2);
        queryParam.put("code", code);
        JSONObject jsonObject = dataQManager.sendDataQApi(HttpMethod.GET, pathUrl, queryParam, null, this.getHeaderMap());
        return jsonObject.getJSONObject("data");
    }

    public JSONObject getTablePhysicsInfoById(String id) {
        String pathUrl = "datamodeling/v4/meta/table/physicsInfo/" + id;
        JSONObject jsonObject = dataQManager.sendDataQApi(HttpMethod.GET, pathUrl, new HashMap<>(2), null, this.getHeaderMap());
        return jsonObject.getJSONObject("data");
    }

    public Map<String, Object> getHeaderMap() {
        Map<String, Object> headerMap = new HashMap<>(16);
        headerMap.put("X-Access-TenantCode", tenantCode);
        headerMap.put("X-Access-WorkspaceId", workspaceId);
        headerMap.put("X-Access-UserId", userId);
        return headerMap;
    }

}
